package com.hitqz.robot.biz.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.base.Objects;
import com.hitqz.robot.api.common.entity.SysMenu;
import com.hitqz.robot.biz.service.SysMenuService;
import com.hitqz.robot.common.core.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author xupkun
 * @date 2024/5/21
 */

@RestController
@AllArgsConstructor
@RequestMapping("/menu")
@Tag(name = "菜单管理")
public class MenuController {

    private final SysMenuService sysMenuService;

    @GetMapping
    @Operation(summary = "获取菜单")
    public R getTree(@RequestParam(value = "type",required = false) String type,@RequestParam(value = "parentId",required = false)  Long parentId) {
        //List<SysMenu> sysMenus = sysMenuService.findMenuByRoleId(1L);
        List<SysMenu> sysMenus = sysMenuService.list(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getDelFlag,"0").orderByDesc(SysMenu::getSortOrder));
        Set<SysMenu> all = new HashSet<>();
        all.addAll(sysMenus);
        return R.ok(sysMenuService.filterMenu(all, type, parentId));
    }


    /**
     * 返回树形菜单集合
     * @param parentId 父节点ID
     * @param menuName 菜单名称
     * @return 树形菜单
     */
    @GetMapping(value = "/tree")
    public R getTree(Long parentId, String menuName, String type) {
        return R.ok(sysMenuService.treeMenu(parentId, menuName, type));
    }

    /**
     * 通过ID查询菜单的详细信息
     * @param id 菜单ID
     * @return 菜单详细信息
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        return R.ok(sysMenuService.getById(id));
    }

    /**
     * 新增菜单
     * @param sysMenu 菜单信息
     * @return success/false
     */
    @PostMapping
    public R save(@Valid @RequestBody SysMenu sysMenu) {
        sysMenuService.save(sysMenu);
        return R.ok(sysMenu);
    }

    /**
     * 删除菜单
     * @param id 菜单ID
     * @return success/false
     */
    @DeleteMapping("/{id}")
    public R removeById(@PathVariable Long id) {
        //菜单管理 不可删除
        if (Objects.equal(id,1L)){
            return R.failed("不允许删除此菜单");
        }
        return sysMenuService.removeMenuById(id);
    }

    /**
     * 更新菜单
     * @param sysMenu
     * @return
     */
    @PutMapping
    public R update(@Valid @RequestBody SysMenu sysMenu) {
        //菜单管理 不可隐藏
        if (Objects.equal(sysMenu.getMenuId(),1L) && Objects.equal(sysMenu.getVisible(),"0")){
            return R.failed("不允许隐藏此菜单");
        }
        return R.ok(sysMenuService.updateMenuById(sysMenu));
    }



}
